
import React, { useEffect, useState } from 'react';
import cls from 'classnames';
// import styles from './index.less'
import Checkbox from './Checkbox';


export interface IOptionProps {
    value?: string | number;
    onChange?: (e: any[]) => void;
    disabled?: boolean;
    size?: 'samll' | 'default' | 'large';
    children?: React.ReactNode;
    className?: any;
    [propName: string]: any;
}

const CheckboxGroup: React.FC<IOptionProps> = (props: IOptionProps) => {
    const { 
        value: currentValue, 
        className, 
        children, 
        disabled, 
        onChange, 
        ...attr 
    } = props;

    const [value, setValue] = useState<any[]>([]);

    useEffect(()=>{
        setValue(getCheckedValue(children))
    },[])

    const getCheckedValue = (children: any) => {
        let checkedValueList: any[] = [];
        //遍历子节点 看是否有选中的值
        React.Children.forEach(children, checkbox => {
            if (
                (checkbox.props && checkbox.props.checked) ||
                checkbox.props.defaultChecked
            ) {
                checkedValueList.push(checkbox.props.value);
            }
        });
        return checkedValueList;
    }

    const onCheckboxChange = (e: any) => {
        const currentValue = e.target.value;
        const currentIndex = value.findIndex(v => v === currentValue);
        //如果没在就加入数组 否则就是 取消选中 删除掉
        if (currentIndex < 0) {
            value.push(currentValue);
        } else {
            value.splice(currentIndex, 1);
        }
        setValue(value);
        onChange && onChange(value);
    };

    const isChecked = value.find(v => v === currentValue);

    const items = React.Children.map(children, (checkbox: any, index) => {
        return (
            <Checkbox
                key={index}
                disabled={disabled}
                {...checkbox.props}
                onChange={onCheckboxChange}
                checked={isChecked}
            />
        );
    });

    return (
        <div className={cls(className)} {...attr}>
            {items}
        </div>
    );
};

CheckboxGroup.defaultProps = {};

export default CheckboxGroup;
